package com.itheima.controller;

import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;

    /**
     * 登录
     *
     * @param user
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user, HttpServletRequest request) {
        try {
            String username = user.getUserName();
            String password = user.getPassWord();
            //校验参数
            if (StringUtils.isEmpty(username)) {
                throw new RuntimeException("请输入用户名");
            }
            if (StringUtils.isEmpty(password)) {
                throw new RuntimeException("请输入密码");
            }
            User user1 = userService.findByUsername(username);
            if(user1 == null){
                return new Result<>(StatusCode.FAIL, "账户密码错误");
            }
            String name = user1.getUserName();

            if (!MD5Utils.md5(password).equals(user1.getPassWord())) {
                return new Result<>(StatusCode.FAIL, "账户密码错误");
            }

            if (user1.getStatus() != 1) {
                throw new RuntimeException("该用户未激活");
            }
            //生成token，并设置token存活时间
            String token = JwtTokenUtils.createToken(name, false);
            //存入到redis当中
            redisTemplate.opsForValue().set("user_" + name, token, JwtTokenUtils.EXPIRATION, TimeUnit.SECONDS);
            CookieUtils.setCookie(CookieUtils.LOGIN_USER, name, (int) JwtTokenUtils.EXPIRATION_REMEMBER);

            //修改登录相关属性
            user1.setLoginCount(user1.getLoginCount() + 1);
            user1.setLastLoginTime(new Date());
            user1.setLastLoginIp(IpUtils.getRealIp(request));
            Map<String, String> osAndBrowserInfo = IpUtils.getOsAndBrowserInfo(request);
            user.setOs(osAndBrowserInfo.get("OS"));
            user.setBrowser(osAndBrowserInfo.get("BROWSER"));
            userService.edit(user1);
            System.out.println("TOKEN"+token);
            return new Result<>("success", "bearer_"+token);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new Result<>(StatusCode.FAIL, "出了点小错");
        }
    }

    /**
     * 注册
     *
     * @param user
     */
    @PostMapping("/register")
    public Result register(@RequestBody User user, HttpServletRequest request) {
        try {
            String username = user.getUserName();
            String password = user.getPassWord();
            //校验参数
            if (StringUtils.isEmpty(username)) {
                throw new RuntimeException("请输入用户名");
            }
            if (StringUtils.isEmpty(password)) {
                throw new RuntimeException("请输入密码");
            }
            if (StringUtils.isEmpty(user.getEmail())) {
                throw new RuntimeException("邮箱号不能为空");
            }

            Map<String, String> osAndBrowserInfo = IpUtils.getOsAndBrowserInfo(request);
            user.setStatus(1);
            user.setOs(osAndBrowserInfo.get("OS"));
            user.setBrowser(osAndBrowserInfo.get("BROWSER"));
            user.setSource("MOGU");
            user.setLoginCount(0);
            user.setLastLoginIp(IpUtils.getRealIp(request));
            userService.register(user);
            return new Result<>(StatusCode.SUCCESS, "注册成功，请登录邮箱进行账号激活");
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new Result<>(StatusCode.FAIL, "该用户名已存在");
        }
    }

}
